package com.mzj.saas.mservice.home.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.house.vo.HousePublicityVO;
import com.mzj.saas.mservice.roles.entity.Role;
import com.mzj.saas.mservice.roles.entity.UserRoleRef;
import com.mzj.saas.mservice.roles.repository.RoleRepository;
import com.mzj.saas.mservice.roles.repository.UserRoleRefRepository;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HomeService {
    private static final Logger LOG = LoggerFactory.getLogger(HomeService.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRoleRefRepository userRoleRefRepository;
    @Autowired
    private AreaRepository areaRepository;

    /*
     * 公告展示
     */
    public ResultBean<Object> companyAdvertShow(String accessToken, List<Integer> typeList, Integer pageNumber,
                                                Integer pageSize) {
        LOG.info("HomeService companyAdvertShow accessToken={},type={},pageNumber={},pageSize={}", accessToken,
                typeList.toArray(), pageNumber, pageSize);
        ResultBean<Object> result = new ResultBean<>();
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            // 企业公告
            if (typeList.size() == 0) {
                typeList.add(1);
            }

            String whereSQL = "";

            String typeValue = "";
            // 社区公告与公租房公示一起展示
            if (typeList.contains(2)) {
                whereSQL = " AND TYPE in (2,5) ";
            } else {
                whereSQL = " AND TYPE =" + typeList.get(0) + " ";
            }

            String columns = " SELECT `id`,`type`,`title`,`home_pic` AS homePic,`content`,`status`, DATE_FORMAT(release_time,'%Y-%m-%d %H:%i:%s')AS releaseTime,area_id AS areaId  FROM `saas_announcement` WHERE  `org_id`=?  "
                    + whereSQL;
            String count = "SELECT COUNT(0) FROM `saas_announcement` WHERE  `org_id`=?  " + whereSQL;
            String offsets = "  LIMIT ? OFFSET ? ";
            columns += "  ORDER BY  `release_time` DESC   ";
            List<Object> args = new ArrayList<>();
            args.add(tokenRedisVo.getEnterpriseId());
            // args.add(type);
            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count, Long.class, args.toArray());
            if (total == 0) {
                result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                result.setResultData(null);
                return result;
            }
            // 查询分页数据
            columns += offsets;
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<Map<String, Object>> maps = jdbcTemplate.queryForList(columns, args.toArray());
            Iterable<Area> areas = areaRepository.findAll();
            for (Map<String, Object> map : maps) {
                for (Area area : areas) {
                    Long areaId = (Long) map.get("areaId");
                    if (area.getId().equals(areaId)) {
                        map.put("areaName", area.getName());
                        break;
                    }

                }
            }

            apiData.setData(maps);
            apiData.setTotal(total);
            result.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 首页企业信息展示
     */
    public ResultBean<Object> companyInformationShow(String accessToken) {
        LOG.info("HomeService companyInformationShow accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        Map<String, Object> map = new HashMap<>();
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }

            User existUser = userRepository.findById(tokenRedisVo.getId());
            if (existUser == null) {
                return ResultBean.failedResultWithMsg("用户信息不存在或已删除");
            }

            Optional<Department> existDepartment = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existDepartment == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            Department department = existDepartment.get();

            String sql = "SELECT id FROM ( SELECT t1.id,IF(FIND_IN_SET(parent_id, @pids) > 0,@pids := CONCAT(@pids, ',', id),0) AS ischild FROM ( SELECT id,parent_id FROM `saas_department` t ORDER BY parent_id, id ) t1,(SELECT @pids := ?) t2 ) t3 WHERE ischild != 0 \n";
            List<Long> ids = jdbcTemplate.queryForList(sql, new Object[]{tokenRedisVo.getEnterpriseId()}, Long.class);
            ids.add(tokenRedisVo.getEnterpriseId());

            // 非离职状态集合
            List<Short> status = new ArrayList<>();
            status.add((short) 0);
            status.add((short) 1);
            StringBuffer depId = new StringBuffer();
            for (Long id : ids) {
                depId.append(id).append(",");
            }
            String depIds = depId.substring(0, depId.lastIndexOf(","));
            // 企业总人数
            String count = "SELECT COUNT(0) FROM `saas_user_department_ref` d INNER JOIN  `saas_user` u ON d.user_id=u.id  WHERE  u.status!=2  AND d.`dep_id` IN ("
                    + depIds + ") ";
            Integer companyPeopleCount = jdbcTemplate.queryForObject(count, Integer.class);
            map.put("companyPeopleCount", companyPeopleCount);
            // 企业部门数
            map.put("companyDepartmentCount", ids != null ? ids.size() - 1 : 0);
            // 企业状态
            map.put("companyStatus", department.getActivateStatus());
            if (tokenRedisVo.getMasterStatus() == 1) {
                map.put("masterUserName", existUser.getName());
            } else {
                String masterUserId = findCompanyMainUserInfo(tokenRedisVo.getEnterpriseId());
                User masterUser = userRepository.findById(masterUserId);
                map.put("masterUserName", masterUser.getName());
            }
            // 子管理员角色Id
            Role childManager = roleRepository.findByOrgIdAndType(tokenRedisVo.getEnterpriseId(), 2);
            List<UserRoleRef> childUserRoleRef = userRoleRefRepository.findByRoleId(childManager.getId());
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (UserRoleRef userRoleRef : childUserRoleRef) {
                User user = userRepository.findById(userRoleRef.getUserId());
                Map<String, Object> userMap = new HashMap<>();
                if (user != null) {
                    userMap.put("childRoleName", user.getName());
                    mapList.add(userMap);
                }
            }
            map.put("childRoleUserList", mapList);
            String countSql = "SELECT COUNT(distinct user_id) FROM saas_enterprise_operation WHERE DATE(operation_time) = DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 DAY), '%Y-%m-%d') AND org_id=?  ";
            Integer yesterdayUseUserCount = jdbcTemplate.queryForObject(countSql,
                    new Object[]{tokenRedisVo.getEnterpriseId()}, Integer.class);
            map.put("yesterdayUseUserCount", yesterdayUseUserCount);
            map.put("companyIcon", department.getIcon());
            map.put("companyName", department.getName());
            map.put("loginUserName", existUser.getName());
            result.setResultData(map);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * 查询企业主管理员用户Id
     */
    public String findCompanyMainUserInfo(Long orgId) {
        String sql = "SELECT DISTINCT ru.user_id FROM saas_user_role_ref ru LEFT JOIN saas_role r ON ru.role_id = r.id WHERE r.org_id = ? AND r.type = 1";
        String userId = jdbcTemplate.queryForObject(sql, new Object[]{orgId}, String.class);
        return userId;
    }

    public ResultBean<Object> housePublicity(String accessToken, Integer pageNumber, Integer pageSize,
                                             HousePublicityVO vo) {
        LOG.info("homeService  housePublicity  accessToken={}, areaId={}", accessToken, vo);

        String SQL = " select * from saas_house_publicity   ";

        String count = " select count(1) from saas_house_publicity  ";

        String offsets = " LIMIT ? OFFSET ?";

        StringBuilder where = new StringBuilder(
                " WHERE 1=1 and area_id =? and  DATE_FORMAT(now(),'%Y%m%d') <= DATE_FORMAT(end_time,'%Y%m%d') ");
        List<Object> args = new ArrayList<>();

        args.add(vo.getAreaId());

        ApiData<HousePublicityVO> apiData = new ApiData<>();

        Long total = jdbcTemplate.queryForObject(count + where, Long.class, args.toArray());
        if (total == 0) {
            return ResultBean.successfulResult(apiData);
        }

        // 查询分页数据
        where.append(" ORDER BY ").append(" end_time desc ").append(" \n").append(offsets);
        args.add(pageSize);
        args.add(pageNumber * pageSize);
        List<HousePublicityVO> data = jdbcTemplate.query(SQL + where,
                new BeanPropertyRowMapper<>(HousePublicityVO.class), args.toArray());

        apiData.setTotal(total);
        apiData.setData(data);
        return ResultBean.successfulResult(apiData);
    }

    /**
     * 产权单位主管理员
     *
     * @param houseId
     * @return
     * @author shun
     * @date 2021年6月22日
     */
    public User findMainUser(String houseId) {
        String sql = "SELECT u.* FROM saas_role r " + "LEFT JOIN saas_user_role_ref f ON f.role_id = r.id "
                + "LEFT JOIN saas_user u ON u.id = f.user_id "
                + "LEFT JOIN  h ON h.org_id = r.org_id WHERE r.type = 1 AND h.id = ?";
        List<User> list = jdbcTemplate.query(sql.toString(), new Object[]{houseId},
                BeanPropertyRowMapper.newInstance(User.class));
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }
}
